package com.alfayun.fiscalriskanalysis.product;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductService {
	
	@Autowired
	private ProductRepository repository;
	
	public List<Product> list() {
		return repository.findAll();
	}
	
	public Product queryById(int id) throws NoSuchProductException {
		return repository.findById(id).orElseThrow(NoSuchProductException::new);
	}
	
	public Product newProduct(Product product) {
		return Product.newProduct(repository, product);
	}

	public void deleteProduct(int id) {
		repository.deleteById(id);
	}

	public Product modifyProduct(int id, Product product) throws NoSuchProductException {
		Optional<Product> row = repository.findById(id);

		if (row.isPresent()) {
			return repository.save(product);
		}

		throw new NoSuchProductException();
	}

	public List<Product> validProducts() {
		return repository.findByStatus(Status.VALID);
	}

}
